package com.lin.reggie.controller;

import com.lin.reggie.common.R;
import com.lin.reggie.entity.User;
import com.lin.reggie.service.UserService;
import com.lin.reggie.util.SMSUtils;
import com.lin.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @RequestMapping("/sendMsg")
    public R<String>sendMsg(@RequestBody User user, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码："+code);
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //将验证码放在缓存里面
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        return R.success("发送验证码成功");
    }

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public R<User>login(@RequestBody Map<String,String>param,HttpSession session){
        //1.取出参数
        String phone = param.get("phone");
        String code = param.get("code");//用户输入的验证码
        //这是会话里获取的String codeInSession = (String) session.getAttribute(phone);
        //从缓存里面获取验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(phone);
        //把参数交给Service,返回当前登录者对象
        User user = userService.login(phone, code, codeRedis);
        //登录成功要做一个登录成功标记
        if (user!=null){
            session.setAttribute("user",user.getId());
            //以前是从会话里删除验证码，现在是从缓存里删除
            //session.removeAttribute(phone);
            redisTemplate.delete(phone);
        }else {
            return R.error("登录失败");
        }
        return R.success(user);
    }



}
